﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Citi.Scheduler.Domain;
using Citi.Helpers;
using System.Configuration;

namespace Citi.Scheduler.WindowsUi.MachineAlert
{
    public partial class CurrentExecution : Form
    {
        public int RoutineExecutionId { get; set; }

        public CurrentExecution(int routineExecutionId)
        {
            this.RoutineExecutionId = routineExecutionId;
            InitializeComponent();
        }

        Timer LogTimer;

        private void CurrentExecution_Load(object sender, EventArgs e)
        {
            lblRoutineName.Text = new RoutineExecution().SelectById<RoutineExecution>(RoutineExecutionId).Routine.Name;
            UpdateLog();

            LogTimer = new Timer { Interval = 10000 };
            LogTimer.Tick += LogTimer_Tick;
            LogTimer.Start();
        }

        void LogTimer_Tick(object sender, EventArgs e)
        {
            UpdateLog();
        }

        int lastId { get; set; }

        private void UpdateLog()
        {
            //var histories = new RoutineExecutionHistory().SelectHistoryByRoutineExecution(routineExecutionId).Where(x => x.Id > lastId).OrderBy(x => x.Date);

            ////lblRoutineName.Text = histories.First().RoutineExecution.Routine.Name;

            //foreach (var history in histories)
            //{
            //    txtLog.AppendText(string.Format("{0} - {1} - {2}", history.Date.ToString("dd/MM/yy HH:mm:ss"),
            //        ((RoutineExecutionStatus)history.Status).GetDescription(), history.Details));
            //    txtLog.AppendText(Environment.NewLine);
            //    lastId = history.Id;
            //}

            var histories = SqlHelper.ExecuteReader(
                string.Format("SELECT Status, Date, Details, Id FROM RoutineExecutionHistory WHERE RoutineExecutionId = {0} AND Id > {1}", RoutineExecutionId, lastId),
                ConfigurationManager.ConnectionStrings["SchedulerConnectionString"].ConnectionString);

            foreach (DataRow row in histories.Rows)
            {
                txtLog.AppendText(string.Format("{0} - {1} - {2}", row[1].ToString(), ((RoutineExecutionStatus)int.Parse(row[0].ToString())).GetDescription(), row[2].ToString()));
                txtLog.AppendText(Environment.NewLine);
                lastId = int.Parse(row[3].ToString());
            }

            txtLog.SelectionStart = txtLog.Text.Length;
            txtLog.ScrollToCaret();
        }
    }
}
